import React, { Component } from 'react'
import * as todoAcitons from '../store/action/todo.action'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { getIn } from 'immutable'

class Header extends Component {
  
  addTodo = (ev) => {
    if(ev.keyCode === 13) {
      // 获取输入框的值
      let taskName = ev.target.value
      if (taskName.trim().length === 0) {
        alert('请输入任务')
        return
      }
      // 异步请求接口
      this.props.add_todo(taskName)
      // 清空输入框
      ev.target.value = ''
    }
  }
  
  render() {
    return (
      <header className="header">
        <h1>todos</h1>
        <input
          onKeyUp={this.addTodo}
          className="new-todo"
          placeholder="What needs to be done?"
          autofocus />
      </header>
    )
  }
}

// 组件与store
const mapStateToProps = (state) => ({
  todos: getIn(state.todoReducer, ['todolist'])
})
// 组件与dispatch
const mapDispatchToProps = (dispatch) => ({
  ...bindActionCreators(todoAcitons, dispatch)
})
export default connect(mapStateToProps, mapDispatchToProps)(Header)